<template>
  <div class="article-list">
    <div class="list-header">
      <h2>文章管理</h2>
      <div class="header-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索文章"
          prefix-icon="Search"
          clearable
          @input="handleSearch"
          style="width: 250px;"
        />
        <el-button type="primary" @click="createNewArticle">
          <el-icon><Plus /></el-icon> 新建文章
        </el-button>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    
    <!-- 错误提示 -->
    <el-alert
      v-if="error"
      title="加载失败"
      type="error"
      :description="error"
      show-icon
      :closable="false"
      style="margin-bottom: 16px;"
    />
    
    <!-- 调试信息 -->
    <div v-if="debugInfo && error" class="debug-info">
      <h3>调试信息:</h3>
      <pre>{{ JSON.stringify(debugInfo, null, 2) }}</pre>
    </div>
    
    <!-- 空状态 -->
    <el-empty 
      v-else-if="articles.length === 0 && !loading && !error" 
      description="暂无文章" 
      :image-size="200"
    >
      <el-button type="primary" @click="createNewArticle">新建文章</el-button>
    </el-empty>
    
    <!-- 文章列表 -->
    <el-table
      v-else-if="articles.length > 0"
      :data="articles"
      style="width: 100%"
      @row-click="handleRowClick"
    >
      <el-table-column prop="title" label="标题" min-width="200">
        <template #default="scope">
          <div class="article-title">
            <el-tag v-if="scope.row.status === 'published'" type="success" size="small">已发布</el-tag>
            <el-tag v-else type="info" size="small">草稿</el-tag>
            <span class="title-text">{{ scope.row.title || '无标题' }}</span>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column prop="created_at" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.created_at) }}
        </template>
      </el-table-column>
      
      <el-table-column prop="updated_at" label="更新时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.updated_at) }}
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button-group>
            <el-button size="small" @click.stop="editArticle(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              type="primary" 
              @click.stop="viewArticle(scope.row)"
              v-if="scope.row.status === 'published'"
            >
              查看
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click.stop="deleteArticle(scope.row)"
            >
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container" v-if="articles.length > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalArticles"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { fetchArticles, deleteArticleById } from '../api/article'

const router = useRouter()

// 状态变量
const articles = ref([])
const loading = ref(true)
const error = ref('')
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalArticles = ref(0)
const debugInfo = ref(null)

// 加载文章列表
const loadArticles = async () => {
  try {
    loading.value = true
    error.value = ''
    debugInfo.value = null
    
    console.log('正在加载文章列表...')
    
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      search: searchQuery.value
    }
    
    console.log('请求参数:', params)
    
    try {
      const response = await fetchArticles(params)
      
      console.log('API 响应:', response)
      
      // 保存调试信息
      debugInfo.value = response
      
      // 检查响应格式
      if (!response || typeof response !== 'object') {
        throw new Error('API 返回了无效的数据格式')
      }
      
      if (!Array.isArray(response.items)) {
        throw new Error('API 返回的 items 不是数组')
      }
      
      articles.value = response.items
      totalArticles.value = response.total || 0
      
      console.log('文章列表加载成功:', articles.value)
    } catch (err) {
      // 如果是 500 错误，尝试显示一个更友好的错误信息
      if (err.message && err.message.includes('500')) {
        error.value = '服务器内部错误，请检查后端日志以获取更多信息'
        
        // 尝试加载一些测试数据，以便用户可以看到界面
        articles.value = [
          {
            id: 'test-1',
            title: '测试文章 1',
            content: '这是一篇测试文章',
            status: 'draft',
            created_at: new Date().toISOString(),
            updated_at: new Date().toISOString()
          },
          {
            id: 'test-2',
            title: '测试文章 2',
            content: '这是另一篇测试文章',
            status: 'published',
            created_at: new Date().toISOString(),
            updated_at: new Date().toISOString()
          }
        ]
        totalArticles.value = 2
      } else {
        throw err // 重新抛出其他类型的错误
      }
    }
  } catch (err) {
    console.error('加载文章失败', err)
    error.value = '加载文章失败: ' + (err.message || '未知错误')
    articles.value = [] // 清空文章列表
    totalArticles.value = 0
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  loadArticles()
}

// 处理分页
const handleSizeChange = (size) => {
  pageSize.value = size
  loadArticles()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadArticles()
}

// 行点击事件
const handleRowClick = (row) => {
  editArticle(row)
}

// 创建新文章
const createNewArticle = () => {
  router.push('/articles/new')
}

// 编辑文章
const editArticle = (article) => {
  router.push(`/articles/${article.id}/edit`)
}

// 查看文章
const viewArticle = (article) => {
  router.push(`/articles/${article.id}`)
}

// 删除文章
const deleteArticle = (article) => {
  ElMessageBox.confirm(
    `确定要删除文章 "${article.title || '无标题'}" 吗？此操作不可恢复。`,
    '删除确认',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteArticleById(article.id)
      ElMessage.success('文章已删除')
      loadArticles()
    } catch (err) {
      console.error('删除文章失败', err)
      ElMessage.error('删除文章失败: ' + (err.message || '未知错误'))
    }
  }).catch(() => {
    // 用户取消删除
  })
}

onMounted(() => {
  console.log('ArticleList 组件已挂载')
  loadArticles()
})
</script>

<style scoped>
.article-list {
  padding: 24px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header-actions {
  display: flex;
  gap: 16px;
}

.loading-container {
  padding: 20px;
}

.article-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-text {
  font-weight: 500;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.debug-info {
  margin: 20px 0;
  padding: 16px;
  background-color: #f8f8f8;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: auto;
}

.debug-info pre {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-word;
}
</style> 